package com.jyu.apts.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.jyu.apts.dao.UserRepository;
import com.jyu.apts.entity.User;
import com.jyu.apts.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserRepository userDao;

	@Override
	public User findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	@Override
	public Page<User> getUserPage(Integer pageNumber, Integer pageSize, Long role_id, Long organizationId, String search) {
		if(pageNumber == null || pageNumber <= 0) {
			pageNumber = 1;
		}
		if(pageSize == null || pageSize <= 0) {
			pageSize = 10;
		}
		Sort sort = new Sort(Sort.Direction.ASC,"id");
		PageRequest pageRequest = new PageRequest(pageNumber-1,pageSize,sort);
		Specification<User> spec = new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate pre = criteriaBuilder.conjunction();
				if(role_id!=null) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.equal(root.get("role").get("id"), role_id.longValue()));
				}
				if(organizationId!=null) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.equal(root.get("organization").get("id"), organizationId.longValue()));
				}
				if(search!=null && search.trim().length()!=0) {
					Predicate or_pre = criteriaBuilder.disjunction(); 
					or_pre =criteriaBuilder.or(or_pre,criteriaBuilder.like(root.get("nickname"), "%"+search+"%"));
					or_pre =criteriaBuilder.or(or_pre,criteriaBuilder.like(root.get("username"), "%"+search+"%"));
					or_pre =criteriaBuilder.or(or_pre,criteriaBuilder.like(root.get("phone"), "%"+search+"%"));
					pre = criteriaBuilder.and(pre,or_pre);
				}
				return pre;
			}
			
		};
		return userDao.findAll(spec, pageRequest);
	}

	@Override
	public void save(User user) {
		userDao.saveAndFlush(user);
	}
	
	@Override
	public void save(List<User> users) {
		userDao.saveAll(users);
		userDao.flush();
	}

	@Override
	public User getOne(long id) {
		return userDao.findById(id).get();
	}

	@Override
	public void delete(List<User> users) {
		userDao.deleteAll(users);
	}

	@Override
	public void delete(User user) {
		userDao.delete(user);
	}

	@Override
	public List<User> findAllById(List<Long> ids) {
		return userDao.findAllById(ids);
	}


}
